package net.wanho.util;

import cn.hutool.json.JSONUtil;
import net.wanho.vo.AjaxResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2023-07-27 17:02
 * Description：ServletUtils工具类
 */
public class ServletUtils {

    public static ServletRequestAttributes getAttributes(){
        return (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); // RequestContextHolder
    }

    /**
     * 获取请求对象
     * @return
     */
    public static HttpServletRequest getRequest(){
        return getAttributes().getRequest();
    }

    /**
     * 获取响应对象
     * @return
     */
    public static HttpServletResponse getResponse(){
        return getAttributes().getResponse();
    }

    /**
     * 响应json数据
     * @param ajaxResult
     */
    public static void writeJson(AjaxResult ajaxResult){
        HttpServletResponse response = getResponse();
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
        } catch (IOException e) {
            throw new RuntimeException("响应AjaxResult失败");
        }
    }

}
